//MegaMek - Copyright (C) 2000,2001,2002,2003,2004 Ben Mazur (bmazur@sev.org)

package megamek.common.actions;

import megamek.common.Building;
import megamek.common.Compute;
import megamek.common.Coords;
import megamek.common.CriticalSlot;
import megamek.common.Entity;
import megamek.common.EntityWeightClass;
import megamek.common.IGame;
import megamek.common.IHex;
import megamek.common.Mech;
import megamek.common.Player;
import megamek.common.TargetRoll;
import megamek.common.Targetable;
import megamek.common.Terrains;
import megamek.common.ToHitData;

// TODO: Auto-generated Javadoc
/**
 * The attacker pushes the target.
 */
public class PushAttackAction extends DisplacementAttackAction {
    /**
     * Static Serial.
     */
    private static final long serialVersionUID = 6878038939232914083L;

    /**
     * Instantiates a new push attack action.
     *
     * @param entityId the entity id
     * @param targetId the target id
     * @param targetPos the target pos
     */
    public PushAttackAction(final int entityId, final int targetId, final Coords targetPos) {
        super(entityId, targetId, targetPos);
    }

    /**
     * Instantiates a new push attack action.
     *
     * @param entityId the entity id
     * @param targetType the target type
     * @param targetId the target id
     * @param targetPos the target pos
     */
    public PushAttackAction(final int entityId, final int targetType, final int targetId,
            final Coords targetPos) {
        super(entityId, targetType, targetId, targetPos);
    }

    /**
     * To hit.
     *
     * @param game the game
     * @return the to hit data
     */
    public final ToHitData toHit(final IGame game) {
        return toHit(game, getEntityId(), game.getTarget(getTargetType(),
                getTargetId()));
    }

    /**
     * pushes are impossible when physical attacks are impossible, or a
     * retractable blade is extended.
     *
     * @param game the game
     * @param aEntity the a entity
     * @param target the target
     * @return the string
     */
    protected static String toHitIsImpossible(final IGame game, final Entity aEntity,
            final Targetable target) {
        String physicalImpossible = PhysicalAttackAction.toHitIsImpossible(
                game, aEntity, target);
        String extendedBladeImpossible = null;
        if (aEntity instanceof Mech && ((Mech) aEntity).hasExtendedRetractableBlade()) {
            extendedBladeImpossible = "Extended retractable blade";
        }
        if (physicalImpossible != null) {
            return physicalImpossible;
        }

        if (aEntity.getGrappled() != Entity.NONE) {
            return "Unit Grappled";
        }

        if (aEntity.isEvading()) {
            return "attacker is evading.";
        }

        if (!game.getOptions().booleanOption("friendly_fire")
				&& target.getTargetType() == Targetable.TYPE_ENTITY
				&& (((Entity) target).getOwnerId() == aEntity.getOwnerId() || (((Entity) target)
						.getOwner().getTeam() != Player.TEAM_NONE
						&& aEntity.getOwner().getTeam() != Player.TEAM_NONE && aEntity
						.getOwner().getTeam() == ((Entity) target).getOwner()
						.getTeam()))) {
			return "A friendly unit can never be the target of a direct attack.";
		}

        return extendedBladeImpossible;
    }

    /**
     * To-hit number for the mech to push another mech.
     *
     * @param game the game
     * @param attackerId the attacker id
     * @param target the target
     * @return the to hit data
     */
    public static ToHitData toHit(final IGame game, final int attackerId, final Targetable target) {
        final Entity aEntity = game.getEntity(attackerId);

        int targetId = Entity.NONE;
        Entity tEntity = null;
        if (target.getTargetType() == Targetable.TYPE_ENTITY) {
            tEntity = (Entity) target;
            targetId = target.getTargetId();
        }

        if (aEntity == null) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "You can't attack from a null entity!");
        }

        IHex attHex = game.getBoard().getHex(aEntity.getPosition());
        IHex targHex = game.getBoard().getHex(tEntity.getPosition());
        final int attackerElevation = aEntity.getElevation() + attHex.getElevation();
        final int targetElevation = target.getElevation()
                + targHex.getElevation();

        boolean inSameBuilding = Compute.isInSameBuilding(game, aEntity, tEntity);
        final boolean targetInBuilding = Compute.isInBuilding(game, tEntity);
        Building bldg = null;
        if (targetInBuilding) {
            bldg = game.getBoard().getBuildingAt(tEntity.getPosition());
        }
        ToHitData toHit = null;

        // can't target yourself
        if (aEntity.equals(tEntity)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "You can't target yourself");
        }

        // non-mechs can't push
        if (!(aEntity instanceof Mech)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Non-mechs can't push");
        }

        // Quads can't push
        if (aEntity.entityIsQuad()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Attacker is a quad");
        }

        // Can only push mechs
        if (!(tEntity instanceof Mech)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is not a mech");
        }

        // Can't push with flipped arms
        if (aEntity.getArmsFlipped()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Arms are flipped to the rear. Can not push.");
        }

        // Can't target a transported entity.
        if (Entity.NONE != tEntity.getTransportId()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Target is a passenger.");
        }

        // Can't target a entity conducting a swarm attack.
        if (Entity.NONE != tEntity.getSwarmTargetId()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Target is swarming a Mek.");
        }

        // check if both arms are present
        if (aEntity.isLocationBad(Mech.LOC_RARM) || aEntity.isLocationBad(Mech.LOC_LARM)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Arm missing");
        }

        // check if attacker has fired arm-mounted weapons
        if (aEntity.weaponFiredFrom(Mech.LOC_RARM)
                || aEntity.weaponFiredFrom(Mech.LOC_LARM)) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Weapons fired from arm this turn");
        }

        // check range
        if (aEntity.getPosition().distance(target.getPosition()) > 1) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target not in range");
        }

        // target must be at same elevation
        if (attackerElevation != targetElevation) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Target not at same elevation");
        }

        // can't push mech making non-pushing displacement attack
        if (tEntity.hasDisplacementAttack() && !tEntity.isPushing()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Target is making a charge/DFA attack");
        }

        // can't push mech pushing another, different mech
        if (tEntity.isPushing()
                && tEntity.getDisplacementAttack().getTargetId() != aEntity.getId()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Target is pushing another mech");
        }

        // can't do anything but counter-push if the target of another attack
        if (aEntity.isTargetOfDisplacementAttack()
                && aEntity.findTargetedDisplacement().getEntityId() != target
						.getTargetId()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Attacker is the target of another push/charge/DFA");
        }

        // can't attack the target of another displacement attack
        if (tEntity.isTargetOfDisplacementAttack()
                && tEntity.findTargetedDisplacement().getEntityId() != aEntity.getId()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Target is the target of another push/charge/DFA");
        }

        // check facing
        if (!target.getPosition().equals(
                aEntity.getPosition().translated(aEntity.getFacing()))) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "Target not directly ahead of feet");
        }

        // can't push while prone
        if (aEntity.isProne()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Attacker is prone");
        }

        // can't push prone mechs
        if (tEntity.isProne()) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Target is prone");
        }

        // Can't target units in buildings (from the outside).
        if (targetInBuilding) {
            if (!Compute.isInBuilding(game, aEntity)) {
                return new ToHitData(TargetRoll.IMPOSSIBLE,
                        "Target is inside building");
            } else if (!game.getBoard().getBuildingAt(aEntity.getPosition()).equals(
                    bldg)) {
                return new ToHitData(TargetRoll.IMPOSSIBLE,
                        "Target is inside differnt building");
            }
        }

        // Attacks against adjacent buildings automatically hit.
        if (target.getTargetType() == Targetable.TYPE_BUILDING
                || target.getTargetType() == Targetable.TYPE_FUEL_TANK) {
            return new ToHitData(TargetRoll.IMPOSSIBLE,
                    "You can not push a building (well, you can, but it won't do anything).");
        }

        // Can't target woods or ignite a building with a physical.
        if (target.getTargetType() == Targetable.TYPE_BLDG_IGNITE
                || target.getTargetType() == Targetable.TYPE_HEX_CLEAR
                || target.getTargetType() == Targetable.TYPE_HEX_IGNITE) {
            return new ToHitData(TargetRoll.IMPOSSIBLE, "Invalid attack");
        }

        toHit = targetingPositions(game, attackerId, aEntity, targetId, tEntity, targHex,
				inSameBuilding);

        return targetingModifiers(game, target, aEntity, tEntity, toHit);
    }

	/**
	 * Targeting positions.
	 *
	 * @param game the game
	 * @param attackerId the attacker id
	 * @param aEntity the a entity
	 * @param targetId the target id
	 * @param tEntity the t entity
	 * @param targHex the targ hex
	 * @param inSameBuilding the in same building
	 * @return the to hit data
	 */
	private static ToHitData targetingPositions(final IGame game, final int attackerId,
			final Entity aEntity, final int targetId, final Entity tEntity, final IHex targHex,
			final boolean inSameBuilding) {
		ToHitData toHit;
		// Set the base BTH
        int base = aEntity.getCrew().getPiloting() - 1;

        toHit = new ToHitData(base, "base");

        // attacker movement
        toHit.append(Compute.getAttackerMovementModifier(game, attackerId));

        // target movement
        toHit.append(Compute.getTargetMovementModifier(game, targetId));

        // attacker terrain
        toHit.append(Compute.getAttackerTerrainModifier(game, attackerId));

        // target terrain
        toHit.append(Compute.getTargetTerrainModifier(game, tEntity, 0, inSameBuilding));

        // damaged or missing actuators
        if (!aEntity.hasWorkingSystem(Mech.ACTUATOR_SHOULDER, Mech.LOC_RARM)) {
            toHit.addModifier(2, "Right Shoulder destroyed");
        }
        if (!aEntity.hasWorkingSystem(Mech.ACTUATOR_SHOULDER, Mech.LOC_LARM)) {
            toHit.addModifier(2, "Left Shoulder destroyed");
        }

        // attacker is spotting
        if (aEntity.isSpotting()) {
            toHit.addModifier(+1, "attacker is spotting");
        }

        // water partial cover?
        if (tEntity.height() > 0 && tEntity.getElevation() == -1
                && targHex.terrainLevel(Terrains.WATER) == tEntity.height()) {
            toHit.addModifier(3, "target has partial cover");
        }
		return toHit;
	}

	/**
	 * Targeting modifiers.
	 *
	 * @param game the game
	 * @param target the target
	 * @param aEntity the a entity
	 * @param tEntity the t entity
	 * @param toHit the to hit
	 * @return the to hit data
	 */
	private static ToHitData targetingModifiers(final IGame game, final Targetable target,
			final Entity aEntity, final Entity tEntity, final ToHitData toHit) {
		// target immobile
        toHit.append(Compute.getImmobileMod(tEntity));

        Compute.modifyPhysicalBTHForAdvantages(aEntity, tEntity, toHit, game);

        //evading
        if (tEntity.isEvading()) {
            toHit.addModifier(tEntity.getEvasionBonus(), "target is evading");
        }

        toHit.append(nightModifiers(game, target, null, aEntity, false));
        // side and elevation shouldn't matter

        // If it has a torso-mounted cockpit and two head sensor hits or three
        // sensor hits, it gets a -4 penalty for being blind!
        if (((Mech) aEntity).getCockpitType() == Mech.COCKPIT_TORSO_MOUNTED) {
            int sensorHits = aEntity.getBadCriticals(CriticalSlot.TYPE_SYSTEM,
                    Mech.SYSTEM_SENSORS, Mech.LOC_HEAD);
            int sensorHits2 = aEntity.getBadCriticals(CriticalSlot.TYPE_SYSTEM,
                    Mech.SYSTEM_SENSORS, Mech.LOC_CT);
            if ((sensorHits + sensorHits2) == 3) {
                return new ToHitData(TargetRoll.IMPOSSIBLE,
                        "Sensors Completely Destroyed for Torso-Mounted Cockpit");
            } else if (sensorHits == 2) {
                toHit.addModifier(4,
                        "Head Sensors Destroyed for Torso-Mounted Cockpit");
            }
        }

        //Attacking Weight Class Modifier.
        if (game.getOptions().booleanOption("tacops_attack_physical_psr")) {
            if (aEntity.getWeightClass() == EntityWeightClass.WEIGHT_LIGHT) {
                toHit.addModifier(-2, "Weight Class Attack Modifier");
            } else if (aEntity.getWeightClass() == EntityWeightClass.WEIGHT_MEDIUM) {
                toHit.addModifier(-1, "Weight Class Attack Modifier");
            }
        }

        if (((Mech) aEntity).hasIndustrialTSM()) {
            toHit.addModifier(2, "industrial TSM");
        }

        // done!
        return toHit;
	}
}
